package work.month07.day02;

import java.sql.PreparedStatement;
import java.sql.ResultSet;
import java.sql.SQLException;

/**
 * @date 2020/07/02
 * @author 王光浩
 * @introduction 将 Student 对象持久化到数据库
 */
public class StudentDaoDatabase implements StudentDao{

	private JDBCHelper helper = null;
	private DataBaseType type = DataBaseType.MYSQL;  // 默认持久化到 MySQL 中
	
	public StudentDaoDatabase(DataBaseType type) {
		this.type = type;
		helper = JDBCHelper.getInstance(type);
	}
	
	public StudentDaoDatabase() {
		helper = JDBCHelper.getInstance(type);
	}

	/**
	 * 向数据库中插入 Student 对象
	 */
	@Override
	public boolean save(Student s) {
		if (s == null)
			throw new IllegalArgumentException("参数 s 不能为空");
		PreparedStatement preparedStatement = null;
		int ret = 0;
		// 1. 获取 PreparedStatement 对象
		String sql = "INSERT INTO student (id , name , gender , birthday) VALUES (? , ? , ? , ?)";
		preparedStatement = helper.getPreparedStatement(sql);
		// 2. 设置相关值
		try {
			preparedStatement.setInt(1, s.getId());
			preparedStatement.setString(2, s.getName());
			preparedStatement.setString(3, s.getGender());
			preparedStatement.setDate(4, s.getBirthday());
		// 3. 执行 语句
			ret = preparedStatement.executeUpdate();
		} catch (SQLException e) {			
			e.printStackTrace();
		} finally {
			helper.close(preparedStatement);
		}
		return ret != 0;
	}

	
	@Override
	public Student find(Integer id) {
		if (id == null)
			throw new IllegalArgumentException("参数 s 不能为空");
		Student s = null;
		PreparedStatement preparedStatement = null;
		ResultSet result = null;
		// 1. 获取 PreparedStatement 对象
		String sql = "SELECT id, name, gender, birthday FROM student";
		preparedStatement = helper.getPreparedStatement(sql);
		// 2. 执行 语句，获取结果集
		try {
			result = preparedStatement.executeQuery();
			while (result.next()) {
				Integer value = result.getInt("id");
				if (id.equals(value)) {
					s = new Student();
					s.setId(value);
					s.setName(result.getString("name"));
					s.setGender(result.getString("gender"));
					s.setBirthday(result.getDate("birthday"));
					return s;
				}
			}
		} catch (SQLException e) {
			e.printStackTrace();
		} finally {
			helper.close(result);
			helper.close(preparedStatement);
		}
		
		return s;
	}
	
	/**
	 * 释放相关资源
	 */
	public void close() {
		helper.close();
	}
	
}
